/*
 *@author: YangJie
 *@date: 2021-04-09 10:49:49
 *@version:
 *@description: 参数设置->公共配置->班组
 */
import React, { Component } from 'react';
import { Table, Form, Card, Tabs,  Row, Col, } from 'antd';
import '@/assets/css/settings';
import * as Utils from '../../utils_yyr/action';
import BasicForm from '../../components_yyr/common/basicFormbaobiao';
import { FileDown } from '../../components_yyr/commponent/File';
import Paging from '../../components_yyr/commponent/Paging';
import PagingLittle from '../../components_yyr/commponent/PagingLittle';
import Echarts from 'echarts-for-react';
// import 'echarts-gl';
import { euqApplicationName_sg, lotAuth, lotAuth2 } from '../../config';

var date = new Date();
let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
let year = date.getFullYear()
let todayEnd = `${year}-${month}-${day} 23:59:59`
let todayStart = `${year}-${month}-01 00:00:00`
let lastMonth = date.getMonth() ? `0${date.getMonth()}` : date.getMonth()
let lastMonthStart = `${year}-${lastMonth}-01 00:00:00`
const { TabPane } = Tabs;
class departmentAnalyse extends Component {

    state = {
        loading: false, //加载中...
        dataSource: [], //数据源
        drawerVisible: false, //新增修改抽屉的显示与隐藏
        chooseData: {}, //用checkbox选择好的数据
        total: 0, //总数据量
        formValues: {},
        weekList: [],
        value: '1',
        //  activeKey:'top',
        activeKey: 'top',
        panes: [],
        newTabIndex: 0,
        equipmentTypeChart: [],
        thisMonth: [], lastMonth: [], last90Day: [], dateString: [], UserList: [], EquTypeList: [],
        loadingRecord: false,
        recordTable: [],
        total1:0,
        formValues1:{}
    };
    constructor(props) {
        super(props);
        // console.log(props);
    }
    componentDidMount() {
        this.getDate()
        this.fetch({
            pageNum: 1,
            pageSize: 10,
            startTime:todayStart,
            endTime:todayEnd,
        });
        this.findInspectionRecordTable({
            pageNum: 1,
            pageSize: 10,
            startTime:todayStart,
            endTime:todayEnd,
        })
        this.queryPageUser()
    }
    //初始化加载数据
    fetch = (data) => {
        let option1 = this.option1
        this.setState({ loading: true, formValues: data})
        this.post(`${euqApplicationName_sg}/planExecutionStatistics/findStatisticsChart`, { data }).then(res => {
            let arr = res.data
            // option1.xAxis.data = arr.map(item => item.dayAll)
            // option1.series[0].data = arr.map(item => item.inspectedCount)
            // option1.series[1].data = arr.map(item => item.actualCount)
            // option1.series[2].data = arr.map(item => item.undetectedCount)
            // option1.series[3].data = arr.map(item => item.abnormalCount)
            option1.dataset.source = arr
            this.setState({ equipmentTypeChart: arr }, () => {
                this.echartRef1.getEchartsInstance().setOption(option1, true);
            })
            console.log(this.state.formValues)
        })
        this.post(`${euqApplicationName_sg}/planExecutionStatistics/findTable`, { data }).then(res => {
            this.setState({
                loading: false,
                dataSource: res.data,
                total: res.total,
            });
            
        })
    }

    findInspectionRecordTable = (data) => {
        this.setState({formValues1:data,loadingRecord:true})
        this.post(`${euqApplicationName_sg}/planExecutionStatistics/findInspectionRecordTable`, { data }).then(res1 => {
            console.log(res1)
            this.setState({
                loadingRecord: false,
                recordTable: res1.data,
                total1: res1.total,
            });
        })
    }
    queryPageUser = () => {
        this.get(`${lotAuth2}/user/queryPageUser?pageNum=1&pageSize=99999`).then(res => {
            this.setState({
                UserList: res.data.data
            });
        })
    }

    getDate = () => {
        var date = new Date();
        let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
        let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
        let year = date.getFullYear()
        let todayEnd = `${year}-${month}-${day} 23:59:59`
        let todayStart = `${year}-${month}-01 00:00:00`
        let thisMonth = [todayStart, todayEnd]
        let lastMonth = this.getLastMonth()
        let last90Day = [this.getLast90Day(), todayEnd]
        this.setState({
            thisMonth, lastMonth, last90Day
        })
        // console.log(todayEnd,todayStart)
        // var dataList = [];
        // for (var i = 0; i < 3; i++) {
        //     var newDate = new Date(date);
        //     newDate.setMonth(date.getMonth() - i);
        //     dataList.unshift(`${newDate.getFullYear()}-${(newDate.getMonth() + 1).toString().padStart(2, '0')}`);
        // }
        // console.log(dataList)
        // console.log(this.getLastMonth())
        // console.log([this.getLast90Day(),todayEnd])
    }
    getLastMonth = () => {//获取上个月日期第一天
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() < 10 ? `0${nowDate.getMonth()}` : nowDate.getMonth();
        if (month == 0) {
            year = year - 1;
            month = 12;
        }
        var lastDay = new Date(year, month, 0);
        var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
        var yyyyMMdd = year + "-" + month + "-" + day + ' 23:59:59';
        return [year + "-" + month + "-01 00:00:00", yyyyMMdd];
    }
    /**
     * 获取上个月月底日期
     */
    getLast90Day = () => {
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() - 2 < 10 ? `0${nowDate.getMonth() - 2}` : nowDate.getMonth() - 2;
        if (month == 0) {
            month = 12;
            year = year - 1;
        }
        var lastDay = new Date(year, month, 0);
        var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
        var yyyyMMdd = year + "-" + month + "-" + day + ' 00:00:00';
        return yyyyMMdd;
    }
    getXianTiOption = () => {
        var colors = ['#fdb6c7','#15bd7f','#f1f131', '#7fd1ff'];
        const option = {
            color: colors,
            title:{
                text:'导出图片',
                show:false
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            grid: {
                right: '2%',
                left: '2%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    // dataView: {show: true, readOnly: false},
                    // restore: {show: true},
                    saveAsImage: { show: true, title: '导出图' }
                }
            },
            legend: {
                data: ['应检次数', '实际次数', '漏检次数', '异常次数']
            },
            dataset: {
                dimensions: ['dayAll', 'inspectedCount', 'actualCount', 'undetectedCount','abnormalCount'],
                source: []
            },
            xAxis: {
                type: 'category',
            },
            yAxis: {},
            series: [
                {
                    name: '应检次数',
                    // data: [],
                    type: 'line',
                    areaStyle: {},
                    label: {
                        show: true,
                    },
                },
                {
                    name: '实际次数',
                    // data: [],
                    type: 'line',
                    label: {
                        show: true,
                    },
                    areaStyle: {}
                },
                {
                    name: '漏检次数',
                    // data: [],
                    type: 'line',
                    label: {
                        show: true,
                    },
                    areaStyle: {}
                },
                {
                    name: '异常次数',
                    // data: [],
                    type: 'line',
                    label: {
                        show: true,
                    },
                    areaStyle: {}
                },
            ],
            dataZoom: [
                {
                    type: 'inside',
                    show: true,
                    xAxisIndex: [0],
                    // 缩放的开始位置的百分比，0 - 100
                    start: 1,
                    // 缩放的结束位置的百分比，0 - 100
                    end: 100,
                    // 缩放的开始位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // startValue?: number,
                    // 缩放的结束位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // endValue?: number
                }
            ]
        };
        this.option1 = option
        return option;
    };

    onChangeTabs = activeKey => {
        console.log(activeKey)
        this.setState({ activeKey });
    };

    onEdit = (targetKey, action) => {
        this[action](targetKey);
    };

    //表单查询
    filterSubmit = values => {
        console.log(values)
        values.startTime = values.startTime_endTime && values.startTime_endTime.length === 2 ? Utils.getDate(values.startTime_endTime[0]) + ' 00:00:00' : ''
        values.endTime = values.startTime_endTime && values.startTime_endTime.length === 2 ? Utils.getDate(values.startTime_endTime[1]) + ' 23:59:59' : ''
        delete values['startTime_endTime']
        let data = { ...this.state.formValues, ...values }
        console.log(data)
        this.fetch(data);
        let data1 = { ...this.state.formValues1, ...values }
        this.findInspectionRecordTable(data1)
    };
    //头部关键字查询部分
    formList = () => {
        const { UserList,formValues } = this.state;
        const formList = [
            { type: "TIMEFRAME", label: "发生时间", field: "startTime_endTime", allowClear: true, initialValue: [formValues.startTime, formValues.endTime] ,required:true},
            {type: 'SELECT', label: '执行人', field: 'executorName',name: 'userName', valueField: 'userName', allowClear: true,list:UserList},
    ];
        return formList;
    };

    onRowClick = (record) => {
        let data = this.state.formValues1
        data.planCode = record.planCode
        this.findInspectionRecordTable(data)
	}
    render() {
        const { chooseData, dataSource, loading, total, formValues ,loadingRecord,total1, formValues1 ,recordTable} = this.state;
        const columns = [
            // { title: '序号', width: 100, dataIndex: 'id' },
            { title: '计划编号', width: 100, dataIndex: 'planCode' ,align:'center',},
            { title: '名称', width: 100, dataIndex: 'planName' ,align:'center',},
            { title: '应巡检次数', width: 100, dataIndex: 'inspectionCount',align:'center', },
            { title: '实际巡检次数', width: 100, dataIndex: 'actualCount',align:'center', },
            { title: '未巡检次数', width: 100, dataIndex: 'noInspectionCount' ,align:'center',},
            { title: '跳过巡检次数', width: 100, dataIndex: 'skipCount' ,align:'center',},
            { title: '异常巡检记录数', width: 100, dataIndex: 'abnormalCount' ,align:'center',},
            { title: '巡检执行率(%)', width: 100, dataIndex: 'inspectionRate',render:(text)=>{
                return <span style={{color:'red'}}>{text}</span>
            },align:'center', },
            { title: '应巡检数', width: 100, dataIndex: 'inspectionsCount' ,align:'center',},
            { title: '实际巡检数', width: 100, dataIndex: 'actualInspectionCount' ,align:'center',},
            { title: '跳过巡检数', width: 100, dataIndex: 'skipNumber' ,align:'center',},
            { title: '覆盖率(%)', width: 100, dataIndex: 'fgRate' ,render:(text)=>{
                return <span style={{color:'red'}}>{text}</span>
            },align:'center', },
        ]
        const columns1 = [
            // { title: '序号', width: 100, dataIndex: 'id' },
            { title: '计划时间', width: 100, dataIndex: 'planTime' ,align:'center',},
            { title: '开始时间', width: 100, dataIndex: 'startTime' ,align:'center',},
            { title: '截止时间', width: 100, dataIndex: 'endTime' ,align:'center',},
            { title: '巡检人', width: 100, dataIndex: 'excutorName',align:'center', },
            { title: '异常设备数', width: 100, dataIndex: 'abnormityNumber',align:'center', },
            { title: '漏检设备数', width: 100, dataIndex: 'omitEquNumber',align:'center', },
            { title: '是否跳过', width: 100, dataIndex: 'whether',align:'center', },
        ]
        return (
            <div className="shadow-radius">
                <Tabs hideAdd
                    onChange={this.onChangeTabs}
                    activeKey={this.state.activeKey}
                    type="editable-card"
                    onEdit={this.onEdit}>
                    <TabPane tab="计划执行统计" key="top" closable={false}>
                        <Card>
                            <BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={ref => (this.child = ref)} />
                        </Card>
                        <div>
                            <Tabs defaultActiveKey="1">
                                <TabPane tab="统计图表" key="1" forceRender>
                                    <div style={{ display: 'flex' }}>
                                        <Echarts
                                            option={this.getXianTiOption()}
                                            style={{ width: '100%', height: '460px' }}
                                            ref={(e) => { this.echartRef1 = e; }}
                                        />
                                    </div>
                                </TabPane>
                                <TabPane tab="巡检记录" key="2" forceRender>
                                    <div style={{ height: '460px' }}>
                                        <Table columns={columns1} rowKey={(record, index) => index} dataSource={recordTable} pagination={false} loading={loadingRecord} style={{ height: '400px' }} scroll={{ y: 300 ,x : 'calc(700px+50%)'}} />
                                        <PagingLittle total={total1} formValues={{...formValues1}} fetch={pager => this.findInspectionRecordTable(pager)}/>
                                    </div>
                                </TabPane>
                            </Tabs>
                        </div>
                        <div>
                            <Row>
                                <Col style={{ float: 'right' }}><FileDown fileName="计划执行统计报表" buttonName="导出表" method="post" apiPath={`${euqApplicationName_sg}/planExecutionStatistics/exportPlanExecutionStatisticsExcel`} data={{...this.state.formValues}} /></Col>
                            </Row>
                        </div>
                        <Table columns={columns} rowKey={(record, index) => record.planCode} dataSource={dataSource} pagination={false} loading={loading} onRowClick={(record)=>{this.onRowClick(record)}}scroll={{ x : 'calc(700px+50%)' }} />
                        <Paging total={total} formValues={{...formValues}} fetch={pager => this.fetch(pager)}  />
                    </TabPane>
                    {this.state.panes.map(pane => (
                        <TabPane tab={pane.title} key={pane.key}>
                            {pane.content}
                        </TabPane>
                    ))}
                </Tabs>
            </div>
        );
    }
}
export default Form.create()(departmentAnalyse);
